/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * principal.java
 *
 * Created on Jan 2, 2012, 3:42:49 PM
 */
package proyecto.so1;

import gramaticas.lex_sgbd;
import gramaticas.lex_sql;
import gramaticas.parser_sgbd;
import gramaticas.parser_sql;
import java.net.*;
import java.io.*;
import java.util.ArrayList;

/**
 *
 * @author Antonio
 */
public class principal extends javax.swing.JFrame {

    public static boolean state, receiveMSG;
    public static String IP1, IP2, IP3, sender;
    private State active;
    private Sync sync;
    private GetCommit gcmt;
    private GetStates gsts;
    private ReceiveMSG rcmsg;
    private GetSenderMSG gsrmsg;
    static public ArrayList<ArrayList> states;
    static public ArrayList<Object> table;
    
    /** Creates new form principal */
    @SuppressWarnings("CallToThreadStartDuringObjectConstruction")
    public principal() {
        initComponents();
        state = true;
        receiveMSG = false;
        IP1="192.168.10.1";
        IP2="192.168.10.2";
        IP3="192.168.10.3";
        states = new ArrayList<ArrayList>();
        active = new State();
        active.start();
        sync = new Sync();
        sync.start();
        rcmsg = new ReceiveMSG();
        rcmsg.start();
        gsrmsg = new GetSenderMSG();
        gsrmsg.start();
        gcmt = new GetCommit();
        gcmt.start();
        synchronize();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        texto = new javax.swing.JTextArea();
        ejecutar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        rb1 = new javax.swing.JRadioButton();
        rb2 = new javax.swing.JRadioButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        texto.setColumns(20);
        texto.setRows(5);
        jScrollPane1.setViewportView(texto);

        ejecutar.setText("Ejecutar");
        ejecutar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ejecutarActionPerformed(evt);
            }
        });

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/SQL.png"))); // NOI18N

        rb1.setSelected(true);
        rb1.setText("SGBD");
        rb1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rb1ActionPerformed(evt);
            }
        });

        rb2.setText("SQL  ");
        rb2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rb2ActionPerformed(evt);
            }
        });

        jLabel2.setText("COMANDOS:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(rb2)
                            .addComponent(jLabel2)
                            .addComponent(rb1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 205, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(ejecutar)
                        .addGap(179, 179, 179))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(51, 51, 51)
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(rb1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                        .addComponent(rb2))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(ejecutar)
                .addGap(72, 72, 72))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-457)/2, (screenSize.height-462)/2, 457, 462);
    }// </editor-fold>//GEN-END:initComponents

private void rb1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rb1ActionPerformed
// TODO add your handling code here:
    rb1.setSelected(true);
    rb2.setSelected(false);
}//GEN-LAST:event_rb1ActionPerformed

private void rb2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rb2ActionPerformed
// TODO add your handling code here:
    rb2.setSelected(true);
    rb1.setSelected(false);
}//GEN-LAST:event_rb2ActionPerformed

public void crearaux() throws FileNotFoundException, IOException {
    
            PrintWriter filOt = null;                        
            File info2 = new File("entrada.txt");            
        try {            
        filOt = new PrintWriter(new FileWriter(info2, false));          
        }  catch (Exception ex) {
            System.err.println(ex.getMessage());
        }
          filOt.write(texto.getText());
           filOt.close();
           filOt=null;
    }



private void ejecutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ejecutarActionPerformed
// TODO add your handling code here:
    try {
          crearaux();
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage());
        } catch (IOException ex) {
        System.out.println(ex.getMessage());
        }
    if(rb1.isSelected()){
                    try {
                        FileReader fileReader = new FileReader("entrada.txt");
                        lex_sgbd scanner = new lex_sgbd(fileReader);
                        parser_sgbd parser = new parser_sgbd(scanner);            
                        try {
                            parser.parse();
                        } catch (Exception ex) {         
                        }
                        fileReader.close();
                        fileReader=null;
                        scanner=null;
                        parser=null;
                    } catch (IOException ex) {
                            System.err.println(""+ex.getMessage().toString());
                            }    
    }else{
    
                    try {
                        FileReader fileReader = new FileReader("entrada.txt");
                        lex_sql scanner = new lex_sql(fileReader);
                        parser_sql parser = new parser_sql(scanner);

                        try {
                            parser.parse();
                            } catch (Exception ex) {         
                            }
                        fileReader.close();
                        fileReader=null;
                        scanner=null;
                        parser=null;
                    } catch (IOException ex) {
                        System.err.println(""+ex.getMessage().toString());
                    }
    }
        
}//GEN-LAST:event_ejecutarActionPerformed

private void synchronize(){
    boolean leftnode = false, rightnode = false;
    try{
        String host = "192.168.1.8";
        Socket client = new Socket(host, 10000);
        client.setReuseAddress(true);
        System.out.println("Connected to " + client.getInetAddress() + " on port "
        + client.getPort() + " from port " + client.getLocalPort() + " of "
        + client.getLocalAddress());
        InputStream input = client.getInputStream();
        DataInputStream data = new DataInputStream(input);
        leftnode = data.readBoolean();
        client.close();
        System.out.println("primer nodo: "+leftnode);
        gsts = new GetStates();
        gsts.start();
        GetData(host);
    }
    catch(Exception e){
        try{
            String host = "192.168.1.20";
            Socket client = new Socket(host, 10000);
            client.setReuseAddress(true);
            System.out.println("Connected to " + client.getInetAddress() + " on port "
            + client.getPort() + " from port " + client.getLocalPort() + " of "
            + client.getLocalAddress());
            InputStream input = client.getInputStream();
            DataInputStream data = new DataInputStream(input);
            rightnode = data.readBoolean();
            client.close();
            System.out.println("segundo nodo: "+rightnode);
            gsts = new GetStates();
            gsts.start();
            GetData(host);
        }
        catch(Exception ex){
            Initialize();
        }
    }
}


private void GetData(String host){
    try{
        Socket client = new Socket(host, 10100);
        InputStream input = client.getInputStream();
        DataInputStream data = new DataInputStream(input);
        int files = data.readInt();
        for(int k=0; k<files; k++){
            String nombre = data.readUTF();
            int length = data.readInt();
            File temp = new File("/var/grupo7/"+nombre);
            FileOutputStream output = new FileOutputStream(temp);
            int paquetes = length/1024;
            byte[] leidos;
            if(paquetes <= 1){
                leidos = new byte[length-1];
                data.read(leidos, 0, length-1);
                output.write(leidos, 0, length-1);
            }
            else{
                int offset = 0;
                for(int i=0; i<paquetes; i++){
                    int end = offset+1023;
                    if(end>length){
                        leidos = new byte[length-offset-1];
                        data.read(leidos, offset, length-1);
                        output.write(leidos, offset, length-1);
                    }
                    else{
                        leidos = new byte[1024];
                        data.read(leidos, offset, end);
                        output.write(leidos, offset, end);
                    }
                }
            }
            output.close();
        }
        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(data));
        states = (ArrayList)in.readObject();
        in.close();
        input.close();
        client.close();
    }
    catch(Exception e){}
}


private void Initialize(){
    table = new ArrayList<Object>();
    try{
        File dir = new File("/var/grupo7");
        File[] list = dir.listFiles();
        for(int k=0; k<list.length; k++){
            File temp = list[k];
            if(temp.isFile()){
                table = new ArrayList<Object>();
                table.add(temp.getName());
                table.add(false);
                table.add(false);
                states.add(table);
            }
        }
    }
    catch(Exception e){}
    
}


public static void Commit(){
    
    for(int k=0; k<states.size(); k++){
        table = states.get(k);
        boolean local = Boolean.getBoolean(table.get(1).toString());
        if(local == true){
            SendCommit scmt = new SendCommit(k);
            scmt.start();
            local = false;
            table.set(1, local);
            table.set(2, local);
            states.set(k, table);
        }
    }
}

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new principal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public static javax.swing.JButton ejecutar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    public static javax.swing.JRadioButton rb1;
    public static javax.swing.JRadioButton rb2;
    public static javax.swing.JTextArea texto;
    // End of variables declaration//GEN-END:variables
}
